//
//  ExchangeAndScoreHistoryController.m
//  NiuBanJin
//
//  Created by Billy on 15/10/16.
//  Copyright © 2015年 zzjr. All rights reserved.
//

#import "ExchangeAndScoreHistoryController.h"
#import "BCSwitchView.h"
#import "ScoreAndExchange.h"
#import "ScoreObtainAndConsumeViewCell.h"

@interface ExchangeAndScoreHistoryController () <UITableViewDataSource,UITableViewDelegate, BCSwitchViewDelegate>

@property (nonatomic, strong) BCSwitchView *view_header;
@property (nonatomic, strong) UIView *view_sep; //分割线
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *mutableArray_data; //数据源
@property (nonatomic, strong) UIView *view_placeHolder;// 没有数据的时候显示的内容

@end

@implementation ExchangeAndScoreHistoryController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self pageSettingsAndSubviewsCreation];
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self getDataFromServer];
}

#pragma mark - data source for current page

- (void) getDataFromServer {
    
    if ([self.type isEqualToString:@"scoreHistory"]) {
        
        // 调用积分接口
        
        [self getAllScoresHistoryOfCurrentUser];
        
    } else {
        
        // 调用兑换加息券接口
        
        [self ticketExchangeHisory];
    }
}

- (void) getAllScoresHistoryOfCurrentUser { //全部积分
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSDictionary *dic_parmas = @{@"token":[UserManager sharedUserManager].user.user_userToken , @"userId" : [UserManager sharedUserManager].user.user_userId , @"offSet" : @"1"};
    
    [[NetworkUtil sharedNetworkUtil] zzjrScore_getscorebyuserByParmeteres:dic_parmas transferResultUsingBlock:^(id parsedData, NSError *error) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        if (!error) {
            
            self.mutableArray_data = parsedData;
            
            if ([self.mutableArray_data count] > 0) {
                
                [self.tableView reloadData];
            }else {
                
                [self.tableView addSubview:self.view_placeHolder];
            }
            
        }else {
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            [UsefulUtil showAlertView:error.description];
        }
    
    }];
}

- (void) getRetrievedScoreHistoryOfCurrentUser { //获得的积分
    
    [self.mutableArray_data removeAllObjects]; //因为是复用的，所以清空历史数据
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSDictionary *dic_parmas = @{@"token":[UserManager sharedUserManager].user.user_userToken , @"userId" : [UserManager sharedUserManager].user.user_userId , @"offSet" : @"1"};
    
    [[NetworkUtil sharedNetworkUtil] zzjrScore_getgainlistbyuserByParmeteres:dic_parmas transferResultUsingBlock:^(id parsedData, NSError *error) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        if (!error) {
            
            self.mutableArray_data = parsedData;
            
            if ([self.mutableArray_data count] > 0) {
                
                [self.tableView reloadData];
            }
            
        }else {
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            [UsefulUtil showAlertView:error.description];
        }
        
    }];
    
}

- (void) getConsumedScoreHistoryOfCurrentUser { //消费的积分
    
    [self.mutableArray_data removeAllObjects]; //因为是复用的，所以清空历史数据
    
    NSDictionary *dic_parmas = @{@"token":[UserManager sharedUserManager].user.user_userToken , @"userId" : [UserManager sharedUserManager].user.user_userId , @"offSet" : @"1"};
    
    [[NetworkUtil sharedNetworkUtil] zzjrScore_getcostlistbyuserByParmeteres:dic_parmas transferResultUsingBlock:^(id parsedData, NSError *error) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        if (!error) {
            
            self.mutableArray_data = parsedData;
            
            if ([self.mutableArray_data count] > 0) {
                
                [self.tableView reloadData];
            }
            
        }else {
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            [UsefulUtil showAlertView:error.description];
        }
        
    }];
}

- (void) ticketExchangeHisory {
    
    NSDictionary *dic_parmas = @{@"token":[UserManager sharedUserManager].user.user_userToken , @"userId" : [UserManager sharedUserManager].user.user_userId , @"offSet" : @"1"};
    
    [[NetworkUtil sharedNetworkUtil] zzjrscorechangedByParmeteres:dic_parmas transferResultUsingBlock:^(id parsedData, NSError *error) {
        
        if (!error) {
            
            self.mutableArray_data = parsedData;
            
            if ([self.mutableArray_data count] > 0) {
                
                [self.tableView reloadData];
            }
            
        }else {
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            [UsefulUtil showAlertView:error.description];
        }
    }];
}

#pragma mark - SubviewsCreationAndPageSettings

- (void) pageSettingsAndSubviewsCreation {
    
    [self.navigationItem setTitle:[self.type isEqualToString:@"scoreHistory"] ? @"积分记录" : @"兑换记录" ];
    
    if ([self.type isEqualToString:@"scoreHistory"]) {
        
        [self.view addSubview:self.view_header];
    }
    
    [self.view addSubview:self.view_sep];
    
    [self.view addSubview:self.tableView];
}

#pragma mark - TableView datasource && delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [self.mutableArray_data count];;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView setRowHeight:MULTIPLYHEIGHT(101.0/2)];
    
    static NSString *identifer = @"cell" ;
    
    ScoreObtainAndConsumeViewCell *cell = (ScoreObtainAndConsumeViewCell *) [tableView dequeueReusableCellWithIdentifier:identifer];
    
    if (!cell) {
        
        cell = [[ScoreObtainAndConsumeViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifer];
    }
    
    cell.scoreAndExchange = self.mutableArray_data[indexPath.row];
    
    [self.type isEqualToString:@"scoreHistory"] ? (cell.type = @"scoreHistory") : (cell.type = @"exchangeHistory") ;
    
    return  cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
 
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

#pragma mark - setter methods

- (UIView *)view_placeHolder {
    
    if (!_view_placeHolder) {
        
        _view_placeHolder = [UsefulUtil viewCreationWithFrame:self.tableView.frame backgroundColor:[UIColor lightGrayColor] backGroundImage:nil];
        
        UILabel *label = [[UILabel alloc] init];
        
        [label setText:@"暂无记录"];
        
        [label setCenter:_view_placeHolder.center];
        [_view_placeHolder addSubview:label];
    }
    
    return _view_placeHolder;
}

- (UIView *)view_sep {
    
    if (!_view_sep) {
        
        CGFloat y_sep= 0.0 ;
        
        if ([self.type isEqualToString:@"scoreHistory"]) {
            
            y_sep = CGRectGetMaxY(self.view_header.frame);
        }
        
        _view_sep = [[UIView alloc] initWithFrame:CGRectMake(0, y_sep, SCREEN_WIDTH, MULTIPLYHEIGHT(2.0/2))];
        [_view_sep setBackgroundColor:[UsefulUtil colorWithHexString:@"#bebebe"]];
    }
    
    return _view_sep;
}

- (UITableView *)tableView {
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.view_sep.frame), SCREEN_WIDTH, SCREEN_HEIGHT - CGRectGetMaxY(self.view_sep.frame)) style:UITableViewStylePlain];
        [_tableView setDelegate:self];
        [_tableView setDataSource:self];
        [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [_tableView setBackgroundColor:BASECOLOR];
        [_tableView setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
    }
    
    return  _tableView;
}

- (BCSwitchView *)view_header {
    
    if (!_view_header) {
        
        _view_header = [[BCSwitchView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, MULTIPLYHEIGHT(120.0/2)) Items:@[@"全部",@"获取",@"消费"] scrollColor:[UsefulUtil colorWithHexString:@"#fb4747"]];
        [_view_header setDelegate:self];
    }
    
    return _view_header;
}


- (void)buttonSelected:(UIButton *)button {
    
    UIView *tmp = [button.superview viewWithTag:200];
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [UIView animateWithDuration:0.2 animations:^{
            
            tmp.frame = CGRectMake(button.frame.origin.x, tmp.frame.origin.y, tmp.bounds.size.width, tmp.bounds.size.height);
        }];
        
    });
    
    switch (button.tag) {
            
        case 100: //全部
        {
            [self getAllScoresHistoryOfCurrentUser];
            [self.tableView reloadData];
        }
            break;
            
        case 101: // 获取
        {
            [self getRetrievedScoreHistoryOfCurrentUser];
            [self.tableView reloadData];
        }
            break;
        case 102: //消费
        {
            [self getConsumedScoreHistoryOfCurrentUser];
            [self.tableView reloadData];
        }
            break;
            
        default:
            break;
    }
}

// 滑动手势, 父vc实现
- (void) swiperGestureHandle:(UISwipeGestureRecognizer *) swipe {
    
    //disable swiping
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
